package com.quartet.modules.platform.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.quartet.api.ApiResult;
import com.quartet.modules.alarm.dao.TTerminalAlarmInfoDao;
import com.quartet.modules.alarm.service.TTerminalAlarmInfoService;
import com.quartet.modules.customer.entity.TCustomerInfo;
import com.quartet.modules.customer.service.TCustomerInfoService;
import com.quartet.modules.order.dao.TOrderDao;
import com.quartet.modules.order.entity.TOrder;
import com.quartet.modules.order.service.TOrderService;
import com.quartet.modules.platform.dto.*;
import com.quartet.modules.platform.dto.vo.*;
import com.quartet.modules.service.aspect.AuthKeyValidated;
import com.quartet.modules.service.dao.TServiceClickCountDao;
import com.quartet.modules.service.dto.TServiceClickCountDto;
import com.quartet.modules.service.entity.TServiceInfo;
import com.quartet.modules.service.service.TServiceInfoService;
import com.quartet.modules.stock.entity.TTerminalStock;
import com.quartet.modules.stock.service.TTerminalStockService;
import com.quartet.modules.terminal.entity.TTerminalInfo;
import com.quartet.modules.terminal.service.TTerminalInfoService;
import com.quartet.modules.vehicle.dao.TTerminalPositionInfoDao;
import com.quartet.modules.vehicle.dto.TTerminalPositionInfoDto;
import com.quartet.modules.vehicle.entity.TTerminalPositionInfo;
import com.quartet.modules.vehicle.service.TTerminalPositionInfoService;
import com.quartet.utils.BinaryUtil;
import com.quartet.utils.DateUtil;
import com.quartet.utils.LocaleUtils;
import com.quartet.utils.MyThreadPoolExecutor;
import com.quartet.utils.constant.MapServerConstant;
import com.quartet.utils.enums.AlarmTypeEnum;
import com.quartet.utils.enums.ServiceStatusEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 平台报警信息表(TPlatformAlarmInfo)表控制层
 *
 * @author makejava
 * @since 2021-06-20 18:55:07
 */
@RestController
@RequestMapping("tPlatformStatistics")
@Slf4j
@Api(tags = "业务：平台统计信息")
public class TPlatformStatisticsController {

    @Autowired
    MyThreadPoolExecutor myThreadPoolExecutor;
    /**
     * 服务对象
     */
    @Resource
    private TOrderService tOrderService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalInfoService tTerminalInfoService;

    /**
     * 服务对象
     */
    @Resource
    private TTerminalPositionInfoService tTerminalPositionInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalAlarmInfoService tOtherAlarmInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalStockService tTerminalStockService;
    /**
     * 服务对象
     */
    @Resource
    private TTerminalPositionInfoDao tTerminalPositionInfoDao;
    /**
     * 服务对象
     */
    @Resource
    private TServiceInfoService tServiceInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TCustomerInfoService tCustomerInfoService;
    /**
     * 服务对象
     */
    @Resource
    private TOrderDao tOrderDao;
    /**
     * 服对象
     */
    @Resource
    private TTerminalAlarmInfoDao tTerminalAlarmInfoDao;
    /**
     * 服对象
     */
    @Resource
    private TServiceClickCountDao tServiceClickCountDao;

    final static DateTimeFormatter DF_WEEK_MONTH = DateTimeFormatter.ofPattern("MM-dd");
    /**
     * @return 查询结果
     */
    @PostMapping("/queryPlatformStatisticsData")
    @AuthKeyValidated(value = "statisticalAnalysis", validated = true)
    @ApiOperation("平台统计")
    public ApiResult<TPlatformStatisticsDataDto> queryPlatformStatisticsData(HttpServletRequest request) {
        //header获取customerCode
        String customerCode = request.getHeader("customerCode");
        TPlatformStatisticsDataDto tPlatformStatisticsDataDto = new TPlatformStatisticsDataDto();
        //一、计算平台当前实时数据信息

        List<TOrder> tOrderList = tOrderService.list(new QueryWrapper<TOrder>().lambda().eq(TOrder::getApplicationType, "VehicleApplicationPlatform").eq(TOrder::getCustomerCode, customerCode));
        List<String> orderCodeList = tOrderList.stream().filter(tOrder -> tOrder.getExpireTime().isAfter(LocalDateTime.now())).map(tOrder -> tOrder.getOrderCode()).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(orderCodeList)) {
            return ApiResult.ok();
        }

        List<TServiceInfo> tServiceInfoList = tServiceInfoService.list(new QueryWrapper<TServiceInfo>().lambda().in(TServiceInfo::getOrderCode, orderCodeList).eq(TServiceInfo::getStatus, ServiceStatusEnum.ENABLE.getValue()).eq(TServiceInfo::getServiceType, "statisticalAnalysis"));
        if (CollectionUtils.isEmpty(tServiceInfoList)) {
            return ApiResult.ok();
        }
        orderCodeList = tServiceInfoList.stream().map(TServiceInfo::getOrderCode).distinct().collect(Collectors.toList());
        //1、在线车辆（车辆应用的在线终端）
//        QueryWrapper<TTerminalInfo> queryWrapper = new QueryWrapper();
//        queryWrapper.lambda().in(TTerminalInfo::getOrderCode, orderCodeList).eq(TTerminalInfo::getOnline, TerminalOnLineEnum.ON_LINE.getValue());
//        List<TTerminalInfo> tTerminalInfoList = tTerminalInfoService.list(queryWrapper);

        QueryWrapper<TTerminalStock> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().in(TTerminalStock::getOrderCode, orderCodeList);
        List<String> tTerminalCodeList = tTerminalStockService.list(queryWrapper).stream().map(TTerminalStock::getTerminalCode).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(tTerminalCodeList)) {
            return ApiResult.ok();
        }
        CompletableFuture<TPlatformCurrentRealDataDto> future1 = CompletableFuture.supplyAsync(() -> getPlatformCurrentRealDataDto(tTerminalCodeList), myThreadPoolExecutor.getAsyncExecutor());
//        TPlatformCurrentRealDataDto tPlatformCurrentRealDataDto = getPlatformCurrentRealDataDto(tTerminalCodeList);
//        tPlatformStatisticsDataDto.setTPlatformCurrentRealDataDto(tPlatformCurrentRealDataDto);

        //二、报警类型统计 按日统计过去一周
        CompletableFuture<TPlatformAlarmResponseDto> future2 = CompletableFuture.supplyAsync(() -> tOtherAlarmInfoService.getAlarmInfoLastWeek(tTerminalCodeList), myThreadPoolExecutor.getAsyncExecutor());
//        TPlatformAlarmResponseDto tPlatformAlarmResponseDto = tOtherAlarmInfoService.getAlarmInfoLastWeek();
//        tPlatformStatisticsDataDto.setTPlatformAlarmResponseDto(tPlatformAlarmResponseDto);

        //三、统计日在线率和月在线率
        //获取终端在线率
        CompletableFuture<TPlatformTerminalOnLineRateDto> future3 = CompletableFuture.supplyAsync(() -> tOtherAlarmInfoService.getOnlineRateLastWeek(tTerminalCodeList), myThreadPoolExecutor.getAsyncExecutor());
//        TPlatformTerminalOnLineRateDto tPlatformTerminalOnLineRateDto = tOtherAlarmInfoService.getOnlineRateLastWeek();
//        tPlatformStatisticsDataDto.setTPlatformTerminalOnLineRateDto(tPlatformTerminalOnLineRateDto);
        //获取一周的总里程数和运行时长
        CompletableFuture<TVehicleFunctionDto> future4 = CompletableFuture.supplyAsync(() -> tTerminalPositionInfoService.queryTerminalTimeAndMileage(tTerminalCodeList), myThreadPoolExecutor.getAsyncExecutor());
//        TVehicleFunctionDto tVehicleFunctionDto = tTerminalPositionInfoService.queryTerminalTimeAndMileage(tTerminalCodeList);
//        tPlatformStatisticsDataDto.setTVehicleFunctionDto(tVehicleFunctionDto);
        //四、过去一周车辆状态总时间
        CompletableFuture<TVehicleStatusTotalTimeDto> future5 = CompletableFuture.supplyAsync(() -> tTerminalPositionInfoService.queryVehicleStatusTotalTime(tTerminalCodeList), myThreadPoolExecutor.getAsyncExecutor());
//        TVehicleStatusTotalTimeDto tVehicleStatusTotalTimeDto=tTerminalPositionInfoService.queryVehicleStatusTotalTime(tTerminalCodeList);
//        tPlatformStatisticsDataDto.setTVehicleStatusTotalTimeDto(tVehicleStatusTotalTimeDto);
        //在线、离线、报警状态的设备数量
        CompletableFuture<List<TTerminalStatusNumber>> future6 = CompletableFuture.supplyAsync(() -> tTerminalPositionInfoService.queryTerminalStatusNum(tTerminalCodeList), myThreadPoolExecutor.getAsyncExecutor());
//        List<TTerminalStatusNumber> tTerminalStatusNumberList=tTerminalPositionInfoService.queryTerminalStatusNum();
//        tPlatformStatisticsDataDto.setTTerminalStatusNumberList(tTerminalStatusNumberList);


        future1.thenAccept(tPlatformStatisticsDataDto::setTPlatformCurrentRealDataDto);
        future2.thenAccept(tPlatformStatisticsDataDto::setTPlatformAlarmResponseDto);
        future3.thenAccept(tPlatformStatisticsDataDto::setTPlatformTerminalOnLineRateDto);
        future4.thenAccept(tPlatformStatisticsDataDto::setTVehicleFunctionDto);
        future5.thenAccept(tPlatformStatisticsDataDto::setTVehicleStatusTotalTimeDto);
        future6.thenAccept(tPlatformStatisticsDataDto::setTTerminalStatusNumberList);

        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(future1, future2, future3, future4, future5, future6);
        voidCompletableFuture.join();
//        tPlatformStatisticsDataDto.setTPlatformCurrentRealDataDto(future1.join());
//        tPlatformStatisticsDataDto.setTPlatformAlarmResponseDto(future2.join());
//        tPlatformStatisticsDataDto.setTPlatformTerminalOnLineRateDto(future3.join());
//        tPlatformStatisticsDataDto.setTVehicleFunctionDto(future4.join());
//        tPlatformStatisticsDataDto.setTVehicleStatusTotalTimeDto(future5.join());
//        tPlatformStatisticsDataDto.setTTerminalStatusNumberList(future6.join());
        return ApiResult.ok(tPlatformStatisticsDataDto);

    }

    private TPlatformCurrentRealDataDto getPlatformCurrentRealDataDto(List<String> tTerminalCodeList) {
        long start = System.currentTimeMillis();
        TPlatformCurrentRealDataDto tPlatformCurrentRealDataDto = new TPlatformCurrentRealDataDto();
        //车辆行驶状态
        int vehicleOnLineNum = tTerminalPositionInfoDao.queryVehicleStatusOnLineNum(tTerminalCodeList, BinaryUtil.convert2Binary(Lists.newArrayList(1)));
        tPlatformCurrentRealDataDto.setCurrentVehicleTotal(vehicleOnLineNum);
        //2、所有车辆行驶总里程
//        List<String> terminalCodeList = tTerminalInfoList.stream().map(tTerminalInfo -> tTerminalInfo.getTerminalCode()).collect(Collectors.toList());
//        CompletableFuture<Float> future1 = CompletableFuture.supplyAsync(() -> tTerminalPositionInfoService.queryTotalMileage(tTerminalCodeList));
        float totalMileage = tTerminalPositionInfoService.queryTotalMileage(tTerminalCodeList);
        tPlatformCurrentRealDataDto.setVehicleTotalMileage(totalMileage);
        //3、当前在线设备数目
        int onLineCount = tTerminalPositionInfoDao.queryTerminalOnLineNum(tTerminalCodeList, BinaryUtil.convert2Binary(Lists.newArrayList(1)));
//        int currentOnLineTerminalTotal = tTerminalInfoService.count(new QueryWrapper<TTerminalInfo>().lambda().eq(TTerminalInfo::getOnline, TerminalOnLineEnum.ON_LINE.getValue()).in(TTerminalInfo::getTerminalCode,tTerminalCodeList));
        tPlatformCurrentRealDataDto.setCurrentOnLineTerminalTotal(onLineCount);
        //4、总报警数目
        QueryWrapper<TTerminalPositionInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().isNotNull(TTerminalPositionInfo::getWarningMark).in(TTerminalPositionInfo::getTerminalCode, tTerminalCodeList);
        int alarmTotal = tTerminalPositionInfoService.count(queryWrapper1);
        tPlatformCurrentRealDataDto.setAlarmTotal(alarmTotal);
        log.info("getPlatformCurrentRealDataDto time is：{}", System.currentTimeMillis() - start);
        return tPlatformCurrentRealDataDto;
    }


    /**
     * @return 查询结果
     */
    @PostMapping("/queryPlatformStatisticsInsertData")
//    @AuthKeyValidated(value = "statisticalAnalysis", validated = true)
    @ApiOperation("平台接入数据统计")
    public ApiResult<TPlatformStatisticsInsertDataDto> queryPlatformStatisticsInsertData() {


        //计算出上个月的开始时间和结束时间
        LocalDateTime lastMonthMin = DateUtil.getLastMonthMin(1);
        LocalDateTime lastMonthMax = DateUtil.getLastMonthMax(1);
        //计算上上月的开始时间和结束时间
        LocalDateTime lastLastMonthMin = DateUtil.getLastMonthMin(2);
        LocalDateTime lastLastMonthMax = DateUtil.getLastMonthMax(2);
        TPlatformStatisticsInsertDataDto tPlatformStatisticsInsertDataDto = new TPlatformStatisticsInsertDataDto();
        //1、计算当前客户数和当前客户数同比上月百分比

        int currentCustomerCount1 = tCustomerInfoService.count();
        tPlatformStatisticsInsertDataDto.setCustomerCount(currentCustomerCount1);

        //上期
        QueryWrapper<TCustomerInfo> queryWrappers = new QueryWrapper<>();
        queryWrappers.lambda().ge(TCustomerInfo::getCreateTime, lastLastMonthMin).le(TCustomerInfo::getCreateTime, lastLastMonthMax);
        int currentCustomerCount = tCustomerInfoService.count(queryWrappers);

        //本期
        QueryWrapper<TCustomerInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().ge(TCustomerInfo::getCreateTime, lastMonthMin).le(TCustomerInfo::getCreateTime, lastMonthMax);
        int lastCustomerCount = tCustomerInfoService.count(queryWrapper);

        if (lastCustomerCount == 0 || currentCustomerCount  == 0 ) {
            tPlatformStatisticsInsertDataDto.setCustomerCountPercent(100);
        } else {
            double percent =  ((lastCustomerCount - currentCustomerCount) / lastCustomerCount * 100);
            tPlatformStatisticsInsertDataDto.setCustomerCountPercent((int)percent);
        }
        //2、计算当前设备总台数和当前设备总台数同比上月百分比
        int currentTerminalCount = tTerminalInfoService.count();
        tPlatformStatisticsInsertDataDto.setTerminalCount(currentTerminalCount);
        //上月
        QueryWrapper<TTerminalInfo> queryWrapper1s = new QueryWrapper<>();
        queryWrapper1s.lambda().ge(TTerminalInfo::getCreateTime, lastLastMonthMin).le(TTerminalInfo::getCreateTime, lastLastMonthMax);
        int lastTerminalCounts = tTerminalInfoService.count(queryWrapper1s);
        //本月
        QueryWrapper<TTerminalInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().ge(TTerminalInfo::getCreateTime, lastMonthMin).le(TTerminalInfo::getCreateTime, lastMonthMax);
        int lastTerminalCount = tTerminalInfoService.count(queryWrapper1);
        if (lastTerminalCount == 0 || lastTerminalCounts == 0) {
            tPlatformStatisticsInsertDataDto.setTerminalCountPercent(100);
        } else {
            double percent2 =  ((currentTerminalCount - lastTerminalCount - lastTerminalCounts) / lastTerminalCounts * 100);
            tPlatformStatisticsInsertDataDto.setTerminalCountPercent((int)percent2);
        }
        //3、计算本月新增设备数和本月新增设备数同比上月百分比
        //计算本月开始时间结束时间
        LocalDateTime lastMonthMinB = DateUtil.getLastMonthMin(0);
        LocalDateTime lastMonthMaxB = DateUtil.getLastMonthMax(0);
        QueryWrapper<TTerminalInfo> queryWrapper1b = new QueryWrapper<>();
        queryWrapper1b.lambda().ge(TTerminalInfo::getCreateTime, lastMonthMinB).le(TTerminalInfo::getCreateTime, lastMonthMaxB);
        //本月设备新增数
        int lastTerminalCountb = tTerminalInfoService.count(queryWrapper1b);
        tPlatformStatisticsInsertDataDto.setCurrentMonthAddTerminalCount(lastTerminalCountb);

        if (lastTerminalCount == 0 || lastTerminalCounts == 0) {
            tPlatformStatisticsInsertDataDto.setCurrentMonthAddTerminalCountPercent(100);
        } else {
            double percent3 =  ((lastTerminalCount- lastTerminalCounts) / lastTerminalCounts * 100);
            tPlatformStatisticsInsertDataDto.setCurrentMonthAddTerminalCountPercent((int)percent3);
//          tPlatformStatisticsInsertDataDto.setCurrentMonthAddTerminalCountPercent((currentTerminalCount - lastTerminalCount - lastTerminalCount) / lastTerminalCount);
        }
        //4、计算上月新增设备数和上月新增设备数同比上月百分比
//        QueryWrapper<TTerminalInfo> queryWrapper3 = new QueryWrapper<>();
//        queryWrapper3.lambda().ge(TTerminalInfo::getCreateTime, lastLastMonthMin).le(TTerminalInfo::getCreateTime, lastLastMonthMax);
//        int lastLastTerminalCount = tTerminalInfoService.count(queryWrapper3);
        tPlatformStatisticsInsertDataDto.setLastMonthAddTerminalCount(lastTerminalCount);
        if (lastTerminalCount == 0 || lastTerminalCounts == 0) {
            tPlatformStatisticsInsertDataDto.setLastMonthAddTerminalCountPercent(100);
        } else {
            double percent4 =  ((lastTerminalCount- lastTerminalCounts) / lastTerminalCounts * 100);
            tPlatformStatisticsInsertDataDto.setLastMonthAddTerminalCountPercent((int)percent4);
        }
        //5、计算本月接入数据量和本月接入数据量同比上月百分比
        //本月
        QueryWrapper<TTerminalPositionInfo> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.lambda().ge(TTerminalPositionInfo::getCreateTime, lastMonthMinB).le(TTerminalPositionInfo::getCreateTime, lastMonthMaxB);
        int currentMonthAddDataCounts = tTerminalPositionInfoService.count(queryWrapper4);
        tPlatformStatisticsInsertDataDto.setCurrentMonthAddDataCount(currentMonthAddDataCounts);

        //本月数据接入数据量
        QueryWrapper<TTerminalPositionInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.lambda().ge(TTerminalPositionInfo::getCreateTime, lastMonthMin).le(TTerminalPositionInfo::getCreateTime, lastMonthMax);
        int currentMonthAddDataCount = tTerminalPositionInfoService.count(queryWrapper3);
        //上月接入数据量
        QueryWrapper<TTerminalPositionInfo> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().ge(TTerminalPositionInfo::getCreateTime, lastLastMonthMin).le(TTerminalPositionInfo::getCreateTime, lastLastMonthMax);
        int lastMonthAddDataCount = tTerminalPositionInfoService.count(queryWrapper2);
        if (lastMonthAddDataCount == 0 || currentMonthAddDataCount ==0) {
            tPlatformStatisticsInsertDataDto.setCurrentMonthAddDataCountPercent(100);
        } else {
            double percent5 =  ((currentMonthAddDataCount - lastMonthAddDataCount) / lastMonthAddDataCount * 100);
            tPlatformStatisticsInsertDataDto.setCurrentMonthAddDataCountPercent((int)percent5);
        }
        //6、接入应用数量
        int applicationCount = tOrderDao.queryApplicationCount();
        tPlatformStatisticsInsertDataDto.setApplicationCount(applicationCount);
        //7、在线设备占比 总的设备数 currentTerminalCount
        int onLineCount = tTerminalPositionInfoDao.queryTerminalOnLineNum(null, BinaryUtil.convert2Binary(Lists.newArrayList(1)));
//        double a = (onLineCount/currentTerminalCount * 100);

        DecimalFormat df = new DecimalFormat("0");
        int a = Integer.parseInt(df.format((float)onLineCount/currentTerminalCount * 100)) ;
        tPlatformStatisticsInsertDataDto.setOnlineTerminalPercent(a);
        //8、当日活跃设备数
//        LocalDateTime startTime = DateUtil.getLastDayMin(0);
        LocalDateTime startTime = DateUtil.getLastDayMin(0);
        Integer activeCount =tTerminalPositionInfoDao.queryActiveTerminalCount(startTime);
        tPlatformStatisticsInsertDataDto.setCurrentActiveTerminalCount(activeCount);
        //9、当前在线设备数
        Integer activeCount1 =tTerminalPositionInfoDao.queryActiveTerminalCount1();
        tPlatformStatisticsInsertDataDto.setCurrentOnlineTerminalCount(activeCount1);
        //10、报警数
        Integer alarmCount = tTerminalAlarmInfoDao.queryAlarmCount();
        if(alarmCount == null){
            alarmCount = 0;
        }
        tPlatformStatisticsInsertDataDto.setAlarmCount(alarmCount);
        //11、接入数据
        int insertDataCount = tTerminalPositionInfoService.count();
        tPlatformStatisticsInsertDataDto.setInsertDataCount(insertDataCount);
        return ApiResult.ok(tPlatformStatisticsInsertDataDto);
    }



    /**
     * @return 查询结果
     */
    @PostMapping("/queryPlatformStatisticsInsertChartData")
    @ApiOperation("平台接入图表数据统计")
    public ApiResult<TPlatformStatisticsInsertChartDataDto> queryPlatformStatisticsInsertChartData() {
        TPlatformStatisticsInsertChartDataDto tPlatformStatisticsInsertChartDataDto = new TPlatformStatisticsInsertChartDataDto();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("HH");
        //1、获取近24小时实时接入数据
        StatisticsPositionGroupDataVo statisticsPositionGroupDataVo = new StatisticsPositionGroupDataVo();

        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDateTime startLocalDateTime = localDateTime.minusDays(1);

        List<String> axis = new ArrayList<>(24);
        LinkedHashMap<String, Integer> map1 = get24HourTimeMap(df, localDateTime, axis);
        List<TTerminalPositionInfoDto> tTerminalPositionInfoDtoList = tTerminalPositionInfoDao.queryPositionInfoByHour(startLocalDateTime);

        for (int i = 0; i < tTerminalPositionInfoDtoList.size(); i++) {
            map1.put(tTerminalPositionInfoDtoList.get(i).getCreateTime(),  tTerminalPositionInfoDtoList.get(i).getCount());
        }
//        tTerminalPositionInfoDtoList.forEach(tTerminalPositionInfoDto -> {
//            Integer integer = map1.get(tTerminalPositionInfoDto.getCreateTime());
//            if (!Objects.isNull(integer)) {
//                map1.put(tTerminalPositionInfoDto.getCreateTime(), integer + 1);
//            }
//        });

        statisticsPositionGroupDataVo.setAxis(axis);
        statisticsPositionGroupDataVo.setValueList(new ArrayList<>(map1.values()));
        tPlatformStatisticsInsertChartDataDto.setStatisticsPositionGroupDataVo(statisticsPositionGroupDataVo);
        //2、客户维度的累计在线时长
        List<TCustomerInfo> customerInfoList = tCustomerInfoService.list();
        List<String> customerList=new ArrayList<>();
        List<Integer> timeList=new ArrayList<>();
        customerInfoList.stream().forEach(tCustomerInfo -> {
            QueryWrapper<TOrder> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(TOrder::getCustomerCode,tCustomerInfo.getCustomerCode());
            List<TOrder> tOrderList = tOrderService.list(queryWrapper);
            Set<String> set=new HashSet<>();
            tOrderList.stream().forEach(tOrder -> {
                LocalDateTime startTime = tOrder.getStartTime();
                Integer usePeriod = tOrder.getUsePeriod();
                for (int i=0;i<usePeriod;i++){
                    set.add(DF_WEEK_MONTH.format(startTime.plusMonths(i)));
                }
            });
            customerList.add(tCustomerInfo.getCustomerName());
            timeList.add(set.size()*30*24);

        });
        StatisticsCustomerOnlineTimeDataVo statisticsCustomerOnlineTimeDataVo=new StatisticsCustomerOnlineTimeDataVo();
        statisticsCustomerOnlineTimeDataVo.setAxis(customerList);
        statisticsCustomerOnlineTimeDataVo.setValueList(timeList);
        tPlatformStatisticsInsertChartDataDto.setStatisticsCustomerOnlineTimeDataVo(statisticsCustomerOnlineTimeDataVo);
        //3、前一日在线时长 TODO
        //4、报警类型统计个数
        List<AlarmCountGroupTypeDataVo> alarmCountGroupTypeDataVoList = tTerminalAlarmInfoDao.queryAlarmCountGroupByAlarm();
        StatisticsAlarmTypeGroupDataVo statisticsAlarmTypeGroupDataVo = getStatisticsAlarmTypeGroupDataVo(alarmCountGroupTypeDataVoList);
        tPlatformStatisticsInsertChartDataDto.setStatisticsAlarmTypeGroupDataVo(statisticsAlarmTypeGroupDataVo);
        //5、近24小时服务调用次数
        getServiceClickCountDtoList(tPlatformStatisticsInsertChartDataDto, df, localDateTime, startLocalDateTime);
        //6、近24小时内在线设备数
        getTerminalPositionInfoDtoList(tPlatformStatisticsInsertChartDataDto, df, localDateTime, startLocalDateTime);
        //7、客户维度的报警数量
        List<AlarmCountGroupCustomerDataVo> alarmCountGroupCustomerDataVoList = tTerminalPositionInfoDao.queryAlarmCountGroupCustomer();
        List<String> customerNameList=new ArrayList<>();
        List<Integer> countList3=new ArrayList<>();
        alarmCountGroupCustomerDataVoList.stream().forEach(alarmCountGroupCustomerDataVo -> {
            customerNameList.add(alarmCountGroupCustomerDataVo.getCustomerName());
            countList3.add(alarmCountGroupCustomerDataVo.getCount());
        });
        StatisticsAlarmCountGroupCustomerDataVo statisticsAlarmCountGroupCustomerDataVo=new StatisticsAlarmCountGroupCustomerDataVo();
        statisticsAlarmCountGroupCustomerDataVo.setAxis(customerNameList);
        statisticsAlarmCountGroupCustomerDataVo.setValueList(countList3);
        tPlatformStatisticsInsertChartDataDto.setStatisticsAlarmCountGroupCustomerDataVo(statisticsAlarmCountGroupCustomerDataVo);
        //8、近24小时报警数量
        getAlarmCountGroupTimeDataVoList(tPlatformStatisticsInsertChartDataDto, df, localDateTime, startLocalDateTime);
        return ApiResult.ok(tPlatformStatisticsInsertChartDataDto);
    }

    /**
     * 功能描述: 近24小时报警数量
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/11/29 11:16
     * @param tPlatformStatisticsInsertChartDataDto
     * @param df
     * @param localDateTime
     * @param startLocalDateTime
     * @return void
     */
    private void getAlarmCountGroupTimeDataVoList(TPlatformStatisticsInsertChartDataDto tPlatformStatisticsInsertChartDataDto, DateTimeFormatter df, LocalDateTime localDateTime, LocalDateTime startLocalDateTime) {
        List<AlarmCountGroupTimeDataVo> alarmCountGroupTimeDataVoList = tTerminalAlarmInfoDao.queryAlarmCountGroupTime(startLocalDateTime);
//        List<String> axis1=new ArrayList<>();
//        List<Integer> valueList=new ArrayList<>();
//        alarmCountGroupTimeDataVoList.stream().forEach(alarmCountGroupTimeDataVo -> {
//            axis1.add(alarmCountGroupTimeDataVo.getCreateTime());
//            valueList.add(alarmCountGroupTimeDataVo.getCount());
//        });
        List<String> axis1 = new ArrayList<>(24);
        LinkedHashMap<String, Integer> map2 = get24HourTimeMap(df, localDateTime, axis1);
        alarmCountGroupTimeDataVoList.forEach(alarmCountGroupTimeDataVo -> {
            Integer integer = map2.get(alarmCountGroupTimeDataVo.getCreateTime());
            if (!Objects.isNull(integer)) {
                map2.put(alarmCountGroupTimeDataVo.getCreateTime(), integer + 1);
            }
        });
        StatisticsAlarmCountGroupTimeDataVo statisticsAlarmCountGroupTimeDataVo=new StatisticsAlarmCountGroupTimeDataVo();
        statisticsAlarmCountGroupTimeDataVo.setAxis(axis1);
        statisticsAlarmCountGroupTimeDataVo.setValueList(new ArrayList<>(map2.values()));
        tPlatformStatisticsInsertChartDataDto.setStatisticsAlarmCountGroupTimeDataVo(statisticsAlarmCountGroupTimeDataVo);
    }

    /**
     * 功能描述: 近24小时内在线设备数
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/11/29 11:14
     * @param tPlatformStatisticsInsertChartDataDto
     * @param df
     * @param localDateTime
     * @param startLocalDateTime
     * @return void
     */
    private void getTerminalPositionInfoDtoList(TPlatformStatisticsInsertChartDataDto tPlatformStatisticsInsertChartDataDto, DateTimeFormatter df, LocalDateTime localDateTime, LocalDateTime startLocalDateTime) {
        List<TTerminalPositionInfoDto> tTerminalPositionInfoDtoList1 = tTerminalPositionInfoDao.queryOnLineTerminalGroup(startLocalDateTime, BinaryUtil.convert2Binary(Lists.newArrayList(1)));

        List<String> axis1 = new ArrayList<>(24);
        LinkedHashMap<String, Integer> map2 = get24HourTimeMap(df, localDateTime, axis1);
        for (int i = 0; i < tTerminalPositionInfoDtoList1.size(); i++) {
            map2.put(tTerminalPositionInfoDtoList1.get(i).getCreateTime(),  tTerminalPositionInfoDtoList1.get(i).getCount());
        }
//        tTerminalPositionInfoDtoList1.forEach(tTerminalPositionInfoDto -> {
//            Integer integer = map2.get(tTerminalPositionInfoDto.getCreateTime());
//            if (!Objects.isNull(integer)) {
//                map2.put(tTerminalPositionInfoDto.getCreateTime(), integer + 1);
//            }
//        });
        StatisticsOnlineTerminalCountDataVo statisticsOnlineTerminalCountDataVo=new StatisticsOnlineTerminalCountDataVo();
        statisticsOnlineTerminalCountDataVo.setAxis(axis1);
        statisticsOnlineTerminalCountDataVo.setValueList(new ArrayList<>(map2.values()));
        tPlatformStatisticsInsertChartDataDto.setStatisticsOnlineTerminalCountDataVo(statisticsOnlineTerminalCountDataVo);
    }

    /**
     * 功能描述: 近24小时服务调用次数
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/11/29 11:10
     * @param tPlatformStatisticsInsertChartDataDto
     * @param df
     * @param localDateTime
     * @param startLocalDateTime
     * @return void
     */
    private void getServiceClickCountDtoList(TPlatformStatisticsInsertChartDataDto tPlatformStatisticsInsertChartDataDto, DateTimeFormatter df, LocalDateTime localDateTime, LocalDateTime startLocalDateTime) {
        List<TServiceClickCountDto> tServiceClickCountDtoList = tServiceClickCountDao.queryServiceClickCount24Hour(startLocalDateTime);
        List<String> axis1 = new ArrayList<>(24);
        LinkedHashMap<String, Integer> map2 = get24HourTimeMap(df, localDateTime, axis1);
        tServiceClickCountDtoList.forEach(tServiceClickCountDto -> {
            Integer integer = map2.get(tServiceClickCountDto.getTime());
            if (!Objects.isNull(integer)) {
                map2.put(tServiceClickCountDto.getTime(), integer + 1);
            }
        });
//
//        List<String> timeList1=new ArrayList<>();
//        List<Integer> countList1=new ArrayList<>();
//        tServiceClickCountDtoList.stream().forEach(tServiceClickCountDto -> {
//            timeList1.add(tServiceClickCountDto.getTime());
//            countList1.add(tServiceClickCountDto.getCount());
//        });
        StatisticsServiceClickCountDataVo statisticsServiceClickCountDataVo=new StatisticsServiceClickCountDataVo();
        statisticsServiceClickCountDataVo.setAxis(axis1);
        statisticsServiceClickCountDataVo.setValueList(new ArrayList<>(map2.values()));
        tPlatformStatisticsInsertChartDataDto.setStatisticsServiceClickCountDataVo(statisticsServiceClickCountDataVo);
    }

    private LinkedHashMap<String, Integer> get24HourTimeMap(DateTimeFormatter df, LocalDateTime localDateTime, List<String> axis) {
        LinkedHashMap<String, Integer> map1 = new LinkedHashMap<>(24);
        for (int i = 23; i >= 0; i--) {
            String s = df.format(localDateTime.minusHours(i));
            axis.add(s);
            map1.put(s, 0);
        }
        return map1;
    }

    /**
     * 功能描述: 按照报警类型统计报警个数
     * @author huipanxing huipanxing@chinasofti.com
     * @date 2021/11/11 15:01
     * @param alarmCountGroupTypeDataVoList
     * @return com.quartet.modules.platform.dto.vo.StatisticsAlarmTypeGroupDataVo
     */
    public StatisticsAlarmTypeGroupDataVo getStatisticsAlarmTypeGroupDataVo(List<AlarmCountGroupTypeDataVo> alarmCountGroupTypeDataVoList) {
        Map<Integer, Integer> alarmTypeCountMap = new HashMap<>(32);
        alarmCountGroupTypeDataVoList.forEach(alarmCountGroupTypeDataVo -> {
            String warningMarkStr = alarmCountGroupTypeDataVo.getWarningMarkStr();
            List<Integer> alarmType = JSON.parseArray(warningMarkStr, Integer.class);
            alarmType.forEach(x -> {
                if (alarmTypeCountMap.get(x) == null) {
                    alarmTypeCountMap.put(x, alarmCountGroupTypeDataVo.getCount());
                } else {
                    alarmTypeCountMap.put(x, alarmTypeCountMap.get(x) + alarmCountGroupTypeDataVo.getCount());
                }
            });
        });
        List<String> listKey = new ArrayList<>(32);
        List<Integer> listValue = new ArrayList<>(32);
        if (LocaleUtils.getLocale().startsWith(MapServerConstant.EN)) {
            alarmTypeCountMap.entrySet().forEach(x -> {
                Integer key = x.getKey();
                listKey.add(AlarmTypeEnum.find(String.valueOf(key)).getDescriptionEn());
                listValue.add(x.getValue());
            });
        } else {
            alarmTypeCountMap.entrySet().forEach(x -> {
                Integer key = x.getKey();
                listKey.add(AlarmTypeEnum.find(String.valueOf(key)).getDescription());
                listValue.add(x.getValue());
            });
        }
        StatisticsAlarmTypeGroupDataVo statisticsAlarmTypeGroupDataVo = new StatisticsAlarmTypeGroupDataVo();
        statisticsAlarmTypeGroupDataVo.setAxis(listKey);
        statisticsAlarmTypeGroupDataVo.setValueList(listValue);
        return statisticsAlarmTypeGroupDataVo;
    }
}
